package com.stx.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.stx.common.JwtUtils;
import com.stx.common.PlayerSessionUtil;
import com.stx.pojo.Record;
import com.stx.pojo.Ruanyue;
import com.stx.pojo.vo.DashboardVO;
import com.stx.service.IRuanyueService;
import com.stx.service.RecordService;
import com.stx.service.RuanyueService;
import io.swagger.v3.oas.annotations.Hidden;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

//@Hidden//隐藏接口
@CrossOrigin
@RestController
@Component
@ServerEndpoint("/chat/{playerId}")
public class ScsSocketEndpoint {


    private static RuanyueService ruanyueService;

    private static RecordService recordService;

    private static final JwtUtils jwtUtils = new JwtUtils();

    private ObjectMapper objectMapper = new ObjectMapper();

    @OnOpen
    public void onOpen(Session session, @PathParam("playerId") int playerId) throws IOException {

        System.err.println("open socket connection, playerId: " + playerId);
        PlayerSessionUtil.addPlayerSession(playerId, session);
        //推送数据库的信息
        // session.getAsyncRemote().sendText(String.valueOf(r.nextDouble()));

        // 推送历史记录
        try {
            if (ruanyueService == null) {
                System.err.println("iruanyueService is null");
            }
            int ruaId = ruanyueService.findNumber();
            sendHistory(session, playerId, ruaId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session, @PathParam("playerId") int playerId) throws IOException {
        System.err.println("close socket connection, playerId: " + playerId);
        PlayerSessionUtil.removePlayerSession(playerId);
        session.close();
    }


    private void sendHistory(Session session, int playerId,int ruaId) throws Exception {
        List<Record> list = recordService.findByPlayerId(playerId,ruaId);//期数
        List<Record> list1 = new ArrayList<>(list);
        //List<Record> list2 = list.stream().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        // 计算平均分
        BigDecimal averageScore = new BigDecimal(recordService.calculateAverageScore(list1)).setScale(2, BigDecimal.ROUND_HALF_UP);
        for (Record record : list) {
            DashboardVO vo = new DashboardVO();
            vo.setAvgScore(averageScore);
            vo.setJudeId(record.getJudId());
            vo.setJudeScore(record.getRecScore());
            // 将平均分推送给所有连接的客户端
            session.getAsyncRemote().sendText(objectMapper.writeValueAsString(vo));
        }
    }

    @Autowired
    public void setRecordService(RecordService recordService) {
        ScsSocketEndpoint.recordService = recordService;
    }

    @Autowired
    public void setRuanyueService(RuanyueService ruanyueService) {
        ScsSocketEndpoint.ruanyueService = ruanyueService;
    }
}